package com.wkbb.basic.controller.manage;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.OrgHoliday;
import com.wkbb.basic.service.OrgHolidayService;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.OrgHolidayDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lizhichao
 * @date 2019/8/17
 * @description
 */
@RestController
@Api(description = "组织节假日管理(后台管理)")
@RequestMapping("/basic/{apiVersion}/orgHoliday/manage")
@Slf4j
public class OrgHolidayManageController extends BaseController {

    @Autowired
    private OrgHolidayService orgHolidayService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @ApiOperation("查询指定组织当年节假日信息分页列表")
    @RequestMapping(value = "/getOrgHolidayPageInfoList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<OrgHolidayDto>> getOrgHolidayPageInfoList(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "组织Id",required = true) @RequestParam(name = "orgId",required = true) Long orgId,
            @ApiParam(value = "页码",required = false,defaultValue = "1") @RequestParam(name = "pageNo",required = false,defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数",required = false,defaultValue = "10") @RequestParam(name = "pageSize",required = false,defaultValue = "10") Integer pageSize) {
        log.info("***********OrgHolidayManageController.getOrgHolidayPageInfoList******apiVersion:{},orgId:{}", apiVersion, orgId);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        try {
            Map<String,Object> parms = new HashMap<>();
            parms.put("orgId", orgId);
            return new ResultDTO<>(orgHolidayService.getOrgHolidayPageInfoList(parms,pageNo,pageSize));
        } catch (Exception e) {
            log.error("OrgHolidayManageController.getOrgHolidayPageInfoList**查询指定组织节假日列表", e);
            e.printStackTrace();
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }

    }

    @ApiOperation("增加节假日信息")
    @RequestMapping(value = "/addOrgHoliday", method = RequestMethod.POST)
    public ResultDTO<Object> addOrgHoliday(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "节假日信息",required = false) @RequestBody OrgHolidayDto orgHolidayDto) {

            UserDto userDto = getUserByLogin();
            if (userDto == null) {
                return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
            }
        try {

            log.info("***********OrgHolidayManageController.addOrgHoliday******apiVersion:{},orgHolidayDto:{}", orgHolidayDto);
            //判断名称是否已经存在
            Map<String,Object> mapParms = new HashMap<>();
            mapParms.put("holidayName", orgHolidayDto.getHolidayName());
            mapParms.put("orgId", orgHolidayDto.getOrgId());

            List<OrgHoliday> holidays = orgHolidayService.getHolidayListByMapParams(mapParms);
            if(!holidays.isEmpty()){
                return new ResultDTO(ErrorCode.NAME_EXIST_ERROR);
            }
            if(orgHolidayDto.getHolidayName() == null || orgHolidayDto.getHolidayType() == null|| orgHolidayDto.getStartHolidayDate()
                    == null ||orgHolidayDto.getEndHolidayDate()== null){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            //结束时间不能小于开始时间
            Date startHolidayDate = new SimpleDateFormat("yyyy-MM-dd").parse(orgHolidayDto.getStartHolidayDate());
            Date endHolidayDate = new SimpleDateFormat("yyyy-MM-dd").parse(orgHolidayDto.getEndHolidayDate());
            if(endHolidayDate.compareTo(startHolidayDate) < 0){
                return new ResultDTO(ErrorCode.PARAM_MISMATCH);
            }
            //增加节假日
            orgHolidayService.addOrgHoliday(orgHolidayDto);
            //清空缓存
//            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            redisTemplateUtil.delKeysLike(RedisKeyConstant.WKBB_BASIC_HOLIDAY + "orgId_" + orgHolidayDto.getOrgId() + "*");
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("OrgHolidayManageController.addOrgHoliday**增加节假日信息", e);
            e.printStackTrace();
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation("更新节假日信息")
    @RequestMapping(value = "/updateOrgHoliday", method = RequestMethod.PUT)
    public ResultDTO<Object> updateOrgHoliday(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "节假日信息",required = false) @RequestBody OrgHolidayDto orgHolidayDto) {

        log.info("***********OrgHolidayManageController.updateOrgHoliday******apiVersion:{},orgHolidayDto:{}", orgHolidayDto);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        try {
            if(StringUtil.isEmpty(orgHolidayDto.getHolidayName())){
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }

            //更新
            this.orgHolidayService.updateOrgHoliday(orgHolidayDto);
            //清空缓存
//            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            redisTemplateUtil.delKeysLike(RedisKeyConstant.WKBB_BASIC_HOLIDAY + "orgId_" + orgHolidayDto.getOrgId() + "*");
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("OrgHolidayManageController.updateOrgHoliday**更新节假日信息异常", e);
            e.printStackTrace();
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }

    }

    @ApiOperation("根据id删除节假日信息")
    @RequestMapping(value = "/deleteByPrimaryKey", method = RequestMethod.DELETE)
    public ResultDTO<Object> deleteByPrimaryKey(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "编号id",required = true) @RequestParam(name = "id",required = true) Long id) {
        log.info("***********OrgHolidayManageController.deleteByPrimaryKey******apiVersion:{},id:{}", apiVersion, id);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        try {
            orgHolidayService.deleteByPrimaryKey(id);
            //清空缓存
            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            redisTemplateUtil.delKeysLike(RedisKeyConstant.WKBB_BASIC_HOLIDAY + "orgId_" + orgId + "*");
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("OrgHolidayManageController.deleteByPrimaryKey**根据id删除节假日信息", e);
            e.printStackTrace();
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }

    }
}
